/*******************************************************************************
 * Package: com.song.kkxxpoi.controller
 * Type:    JueJin
 * Date:    2024-02-08 17:00
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.kkxxpoi.controller;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.song.common.annotation.ResponseInfoSkin;
import com.song.common.util.CommUtil;
import com.song.common.util.JsonUtils;
import com.song.common.util.RedisServiceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 功能描述：
 * 掘金
 * https://blog.csdn.net/qq_36624086/article/details/126692040
 * 有道云笔记
 *
 * @author Songxianyang
 * @date 2024-02-08 17:00
 */
@Api(tags = "签到")
@RestController
@RequestMapping("/sign-in")
@Slf4j
@ResponseInfoSkin
public class SignInWeb {
    public static final String COOKIE = ":cookie";
    /**
     * 掘金
     */
    public static final String JUEJIN = "juejin";
    /**
     * 有道
     */
    public static final String YOUDAO = "OUTFOX_SEARCH_USER_ID_NCOO=1225814786.3027349; _ga=GA1.2.1980173259.1672242958; OUTFOX_SEARCH_USER_ID=351554008@120.244.136.237; YNOTE_USER=1; YD00053006227227%3AWM_TID=cbFcD3Ib5S9AAEQAVQOQMo6DZ5ItKjby; Hm_lvt_71b82399c7b3d982f74bb674d575193c=1677459367,1677937300,1679063607; YD00053006227227%3AWM_NI=kCVDpIavg5qnuxHgBXWsFBxuOY1Y0Ju%2FVUslamAXULU5TTQefLN%2Bp4%2Buieep44d7%2F1F3yh8cGuahlrPZ9ZjdNdcGDYNi2ibMFNjDhGY0LaeqIi1WinVTNmVxlviEwyPaOFo%3D; YD00053006227227%3AWM_NIKE=9ca17ae2e6ffcda170e2e6eed4b37c82bca28cc634aeac8ab6d15b879a9f86d174a6f58682cf4db7f59a91ae2af0fea7c3b92aa99d9aa5f343a3aaa9d6f466b7a88888c15495ad8aa3fb7f8d87ffbab342b7f19ab6f268a3b38fb9d84897eb9cb5d46fa69482ccf340e9aba786e87cf8ecacd8ae3b86edb789bb6985abaf89ef7a9486f7bbe9708ebcada8c7538eb7fe8ae1478692a6a5eb4d9bf08482e87b8bb7ffb8ec66968c828ed574b0aaa7a6f67394bf81a7ee37e2a3; YNOTE_PERS=v2|wxoa||YNOTE||web||-1||1687828980151||123.114.201.69||weixinobU7VjrHkXvt8SFJRWcvW7jSw8Js||gZ6LOEh4zm0zMP4QZh4kfReS0HQL0MzM0wBhL6u0MUGRqKhHpFh4Tz0TBPMkGkMgL0euRLYEnMzl0wunMzMkMTu0; P_INFO=null; Hm_lvt_daa6306fe91b10d0ed6b39c4b0a407cd=1699340322; Hm_lvt_30b679eb2c90c60ff8679ce4ca562fcc=1702689300,1704699276; __yadk_uid=3jc51bKvFLDMGzcBIln1K4uQLtDJqYPg; hb_MA-B0D8-94CBE089C042_source=www.baidu.com; YNOTE_SESS=v2|K8PlU8HbRVwy0LOGk4UfRwFOfPLO4pz0kEP4P4hfwZ06LRMpK6LOGRYf6Lg4n4OW0lf0Hk50HPu0QyhLl5kLJS0JKhMTz64PZ0; YNOTE_LOGIN=5||1708391679965; YNOTE_CSTK=GnuAIHkS";
    // 每天9点15开始执行
    public static final String IN_TIME = "0 15 09 ? * *";
    // 每天9点17开始执行
    public static final String DRAW_TIME = "0 17 09 ? * *";
    @Resource
    private RedisServiceUtil redisServiceUtil;

    @SneakyThrows
    @GetMapping("jue-jin-sign-in")
    @ApiOperation("签到")
    @Scheduled(cron = IN_TIME)
    public String signIn() {
        log.info("掘金自动签到开始");
        String str = redisServiceUtil.get(JUEJIN + COOKIE);
        //List<String> list = JSONUtil.toBean(str, List.class);
        List<String> list = JsonUtils.toObject(str, List.class);
        if (CommUtil.isEmpty(list)) {
            return "失败";
        }
        Map<String, String> header = Maps.newHashMap();
        //签到任务接口
        String url = "https://api.juejin.cn/growth_api/v1/check_in";
        for (String id : list) {
            //你的cookie
            String juejinCookie = id;
            RequestBody requestBody = new FormBody.Builder().build();
            String post = post(url, juejinCookie, requestBody, header);
            log.info("执行成功的cookie：{},执行结果为：：{}", id, post);

        }

        return "成功";
    }

    //post请求的工具类方法
    public static String post(String url, String cookie, RequestBody requestBody, Map<String, String> header) throws Exception {

        String userAgent = "okhttp/3.12.1;jdmall;android;version/10.3.4;build/92451;";

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(Headers.of(header))
                .addHeader("Cookie", cookie)
                .addHeader("User-Agent", userAgent)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("connection", "Keep-Alive")
                .addHeader("accept", "*/*")
                .build();

        Response response = client.newCall(request).execute();
        String result = response.body().string();
        log.info("post请求,result:{}", result);
        return result;
    }

    @SneakyThrows
    @GetMapping("jue-jin-lottery-draw")
    @ApiOperation("抽奖")
    @Scheduled(cron = DRAW_TIME)
    public String lotteryDraw() throws Exception {
        log.info("掘金自动抽奖开始");
        String str = redisServiceUtil.get(JUEJIN + COOKIE);
        //List<String> list = JSONUtil.toBean(str, List.class);
        List<String> list = JsonUtils.toObject(str, List.class);
        if (CommUtil.isEmpty(list)) {
            return "失败";
        }
        Map<String, String> header = Maps.newHashMap();
        //抽奖接口
        String drawUrl = "https://api.juejin.cn/growth_api/v1/lottery/draw";
        for (String id : list) {
            //你的cookie
            String juejinCookie = id;
            RequestBody requestBody = new FormBody.Builder().build();
            String response = post(drawUrl, juejinCookie, requestBody, header);
            log.info("执行成功的cookie：{},执行结果为：：{}", id, response);
        }

        return "success";
    }

    @PostMapping("jue-jin-set-cookie")
    @ApiOperation("存掘金cookie")
    public String set(@org.springframework.web.bind.annotation.RequestBody List<String> cookies) {
        String list = JSONUtil.toJsonStr(cookies);
        redisServiceUtil.set(JUEJIN + ":cookie", list);
        return "success";
    }

    @PostMapping("you-dao-set-cookie")
    @ApiOperation("存有道云cookie")
    public String youDaoSet(@org.springframework.web.bind.annotation.RequestBody List<String> cookies) {
        String list = JSONUtil.toJsonStr(cookies);
        redisServiceUtil.set(YOUDAO + ":cookie", list);
        return "success";
    }


    @SneakyThrows
    @GetMapping("you-dao-sign-in")
    @ApiOperation("有道云签到")
    public String youDaoSignIn() {
        log.info("有道云签到");
        Map<String, String> header = Maps.newHashMap();
//签到任务接口
        String url = "https://note.youdao.com/yws/mapi/user?method=checkin";
//你的cookie
        String youDaoCookie = YOUDAO;
        RequestBody requestBody = new FormBody.Builder().build();
        String response = youDaoPost(url, youDaoCookie, requestBody, header);
        return response;
    }

    public static String youDaoPost(String url, String cookie, RequestBody requestBody, Map<String, String> header) throws Exception {
        String userAgent = "ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.0.10191 SLBChan/30";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(Headers.of(header))
                .addHeader("Cookie", cookie)
                .addHeader("User-Agent", userAgent)
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .addHeader("Cache-Control", "no-cache")
                //.addHeader("connection", "Keep-Alive")
                .addHeader("accept", "*/*")
                .addHeader("Host","note.youdao.com")
                .addHeader("Referer","https://note.youdao.com/web/")
                .build();

        Response response = client.newCall(request).execute();
        String result = response.body().string();
        log.info("post请求,result:{}", result);
        return result;
    }
}
